import mongoose from 'mongoose'
import config from '../config'
import fs from 'fs'
import { resolve } from 'path'

const models = resolve(__dirname,  '../database/schema')
fs.readdirSync(models)
.filter(file => ~file.search(/^[^\.].*js$/))
.forEach(file => require(resolve(models, file)))

export const database = app => {
  // let maxConnet = 0
  if (process.env !== 'production') {
    mongoose.set('debug', true)
  }

  mongoose.connect(config.db, { useCreateIndex: true, useNewUrlParser: true })

  mongoose.connection.on('open', async => {
    console.log('Connected to Mongodb', config.db)
  })

  mongoose.connection.on('disconnected', () => {
    mongoose.connect(config.db, { useCreateIndex: true, useNewUrlParser: true })
  })

  mongoose.connection.on('error', error => {
    console.log(error)
  } )
}
